package com.zmj.framework.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.zmj.framework.base.BaseCtrl;
import com.zmj.framework.bean.Log;
import com.zmj.framework.bean.UserSession;
import com.zmj.framework.service.LogManager;

public class LogInterceptor implements HandlerInterceptor {
	@Autowired
	private LogManager logManager;
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		return true;
	}

	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		HandlerMethod handlerMethod=(HandlerMethod)handler;
		String methodName=handlerMethod.getMethod().getName();
		String className=handlerMethod.getBean().getClass().getSimpleName();
		if(handlerMethod.getBean() instanceof BaseCtrl){
			String logInfo = ((BaseCtrl)handlerMethod.getBean()).getLogInfo();
			if(logInfo!=null&&logInfo.length()>0){
				String yhmc="δ֪";
				UserSession userSession = (UserSession) request.getSession().getAttribute("userSession");
				if (userSession != null) {
					yhmc=userSession.getSysuser().getYhmc();
				}
				String ip = request.getRemoteAddr();
				Log log=new Log();
				log.setYhmc(yhmc);
				log.setCzlx(className+":"+methodName);
				log.setCznr(logInfo);
				log.setIp(ip);
				logManager.saveLog(log);
				((BaseCtrl)handlerMethod.getBean()).setLogInfo("");
			}
		}
	}

	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
	}

}